<template>
  <div class="holiday-manage">
    <div class="calendar-header">
      <div class="date-selector">
        <el-date-picker
          v-model="currentDate"
          type="month"
          placeholder="选择年月"
          format="YYYY年MM月"
          value-format="YYYY-MM"
          @change="handleDateChange"
        />
      </div>
      <div class="header-actions">
        <el-button type="primary" @click="showBatchDialog">批量设置</el-button>
        <el-button @click="showStatistics">统计信息</el-button>
      </div>
      <div class="legend">
        <span class="legend-item">
          <span class="legend-color work"></span>
          工作日
        </span>
        <span class="legend-item">
          <span class="legend-color holiday"></span>
          休息日
        </span>
      </div>
    </div>

    <div class="calendar-container">
      <div class="calendar-grid">
        <!-- 星期标题 -->
        <div class="week-header">
          <div class="week-day" v-for="day in weekDays" :key="day">{{ day }}</div>
        </div>
        
        <!-- 日期网格 -->
        <div class="calendar-body">
          <div
            v-for="date in calendarDates"
            :key="date.fullDate"
            :class="[
              'calendar-cell',
              {
                'other-month': !date.isCurrentMonth,
                'today': date.isToday,
                'work-day': date.type === 'work',
                'holiday': date.type === 'holiday'
              }
            ]"
            @click="handleDateClick(date)"
          >
            <div class="date-number">{{ date.day }}</div>
            <div class="date-type">
              <span v-if="date.type === 'work'" class="type-badge work">班</span>
              <span v-if="date.type === 'holiday'" class="type-badge holiday">休</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="编辑"
      width="400px"
      :before-close="handleDialogClose"
    >
      <div class="edit-form">
        <div class="form-item">
          <label>日期：</label>
          <span>{{ selectedDate?.fullDate }}</span>
        </div>
        <div class="form-item">
          <label><span class="required">*</span> 类型：</label>
          <el-radio-group v-model="editForm.type">
            <el-radio value="holiday">休</el-radio>
            <el-radio value="work">班</el-radio>
          </el-radio-group>
        </div>
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleDialogClose">取消</el-button>
          <el-button type="primary" @click="handleSave">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 批量设置对话框 -->
    <el-dialog
      v-model="batchDialogVisible"
      title="批量设置"
      width="500px"
    >
      <div class="batch-form">
        <div class="form-item">
          <label><span class="required">*</span> 日期范围：</label>
          <el-date-picker
            v-model="batchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </div>
        <div class="form-item">
          <label><span class="required">*</span> 类型：</label>
          <el-radio-group v-model="batchForm.type">
            <el-radio value="holiday">休</el-radio>
            <el-radio value="work">班</el-radio>
          </el-radio-group>
        </div>
        <div class="form-item">
          <label>仅设置：</label>
          <el-checkbox-group v-model="batchForm.weekdays">
            <el-checkbox value="1">周一</el-checkbox>
            <el-checkbox value="2">周二</el-checkbox>
            <el-checkbox value="3">周三</el-checkbox>
            <el-checkbox value="4">周四</el-checkbox>
            <el-checkbox value="5">周五</el-checkbox>
            <el-checkbox value="6">周六</el-checkbox>
            <el-checkbox value="0">周日</el-checkbox>
          </el-checkbox-group>
          <div class="tip">不选择则设置范围内所有日期</div>
        </div>
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="batchDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleBatchSave">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 统计信息对话框 -->
    <el-dialog
      v-model="statisticsDialogVisible"
      title="统计信息"
      width="600px"
    >
      <div class="statistics-content" v-if="statisticsData">
        <div class="statistics-item">
          <span class="label">年份：</span>
          <span class="value">{{ statisticsData.year }}年</span>
        </div>
        <div class="statistics-item">
          <span class="label">总工作日：</span>
          <span class="value work">{{ statisticsData.totalWorkDays }}天</span>
        </div>
        <div class="statistics-item">
          <span class="label">总休息日：</span>
          <span class="value holiday">{{ statisticsData.totalHolidays }}天</span>
        </div>
        <div class="statistics-item">
          <span class="label">自定义工作日：</span>
          <span class="value">{{ statisticsData.customWorkDays }}天</span>
        </div>
        <div class="statistics-item">
          <span class="label">自定义休息日：</span>
          <span class="value">{{ statisticsData.customHolidays }}天</span>
        </div>
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="statisticsDialogVisible = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { ElMessage } from 'element-plus'
import dayjs from 'dayjs'
import * as holidayApi from '@/api/modules/holiday'

interface CalendarDate {
  fullDate: string
  day: number
  isCurrentMonth: boolean
  isToday: boolean
  type: 'work' | 'holiday' | null
}

interface EditForm {
  type: 'work' | 'holiday'
}

interface BatchForm {
  dateRange: [string, string] | null
  type: 'work' | 'holiday'
  weekdays: string[]
}

interface StatisticsData {
  year: number
  totalWorkDays: number
  totalHolidays: number
  customWorkDays: number
  customHolidays: number
}

// 响应式数据
const currentDate = ref(dayjs().format('YYYY-MM'))
const dialogVisible = ref(false)
const batchDialogVisible = ref(false)
const statisticsDialogVisible = ref(false)
const selectedDate = ref<CalendarDate | null>(null)
const editForm = ref<EditForm>({ type: 'work' })
const batchForm = ref<BatchForm>({ dateRange: null, type: 'work', weekdays: [] })
const holidayData = ref<Record<string, 'work' | 'holiday'>>({})
const statisticsData = ref<StatisticsData | null>(null)

// 星期标题
const weekDays = ['一', '二', '三', '四', '五', '六', '日']

// 计算日历数据
const calendarDates = computed(() => {
  const dates: CalendarDate[] = []
  const currentMonth = dayjs(currentDate.value)
  const startOfMonth = currentMonth.startOf('month')
  const endOfMonth = currentMonth.endOf('month')
  
  // 获取月初是星期几（0=周日，1=周一...）
  const startWeekday = startOfMonth.day()
  // 转换为周一开始（0=周一，1=周二...）
  const mondayStartWeekday = startWeekday === 0 ? 6 : startWeekday - 1
  
  // 添加上个月的日期
  for (let i = mondayStartWeekday - 1; i >= 0; i--) {
    const date = startOfMonth.subtract(i + 1, 'day')
    dates.push({
      fullDate: date.format('YYYY-MM-DD'),
      day: date.date(),
      isCurrentMonth: false,
      isToday: date.isSame(dayjs(), 'day'),
      type: holidayData.value[date.format('YYYY-MM-DD')] || getDefaultType(date)
    })
  }
  
  // 添加当月的日期
  for (let i = 0; i < endOfMonth.date(); i++) {
    const date = startOfMonth.add(i, 'day')
    dates.push({
      fullDate: date.format('YYYY-MM-DD'),
      day: date.date(),
      isCurrentMonth: true,
      isToday: date.isSame(dayjs(), 'day'),
      type: holidayData.value[date.format('YYYY-MM-DD')] || getDefaultType(date)
    })
  }
  
  // 添加下个月的日期，补齐6行
  const totalCells = 42 // 6行 × 7列
  const remainingCells = totalCells - dates.length
  for (let i = 0; i < remainingCells; i++) {
    const date = endOfMonth.add(i + 1, 'day')
    dates.push({
      fullDate: date.format('YYYY-MM-DD'),
      day: date.date(),
      isCurrentMonth: false,
      isToday: date.isSame(dayjs(), 'day'),
      type: holidayData.value[date.format('YYYY-MM-DD')] || getDefaultType(date)
    })
  }
  
  return dates
})

// 获取默认类型（周末为休息日，工作日为工作日）
const getDefaultType = (date: dayjs.Dayjs): 'work' | 'holiday' => {
  const weekday = date.day()
  return weekday === 0 || weekday === 6 ? 'holiday' : 'work'
}

// 处理日期变化
const handleDateChange = (value: string) => {
  currentDate.value = value
  loadHolidayData()
}

// 处理日期点击
const handleDateClick = (date: CalendarDate) => {
  selectedDate.value = date
  editForm.value.type = date.type || 'work'
  dialogVisible.value = true
}

// 处理对话框关闭
const handleDialogClose = () => {
  dialogVisible.value = false
  selectedDate.value = null
}

// 保存设置
const handleSave = () => {
  if (!selectedDate.value) return
  
  const dateKey = selectedDate.value.fullDate
  holidayData.value[dateKey] = editForm.value.type
  
  // 这里应该调用API保存到后端
  saveHolidayData(dateKey, editForm.value.type)
  
  ElMessage.success('设置成功')
  dialogVisible.value = false
}

// 加载假期数据
const loadHolidayData = async () => {
  try {
    const response = await holidayApi.getHolidayData({ yearMonth: currentDate.value })
    if (response.data) {
      // 转换数据格式
      const newHolidayData: Record<string, 'work' | 'holiday'> = {}
      Object.keys(response.data).forEach(date => {
        newHolidayData[date] = response.data[date].type
      })
      holidayData.value = newHolidayData
    }
  } catch (error: any) {
    // 忽略请求取消错误，这是正常的用户交互行为
    if (error.name === 'CanceledError' || error.code === 'ERR_CANCELED') {
      console.log('请求被取消，用户切换了月份')
      return
    }
    console.error('加载假期数据失败:', error)
    ElMessage.error('加载假期数据失败')
  }
}

// 保存假期数据
const saveHolidayData = async (date: string, type: 'work' | 'holiday') => {
  try {
    await holidayApi.saveHolidayData({ date, type })
  } catch (error) {
    console.error('保存假期数据失败:', error)
    ElMessage.error('保存失败')
    throw error
  }
}

// 显示批量设置对话框
const showBatchDialog = () => {
  batchForm.value = { dateRange: null, type: 'work', weekdays: [] }
  batchDialogVisible.value = true
}

// 显示统计信息
const showStatistics = async () => {
  try {
    const year = dayjs(currentDate.value).year()
    const response = await holidayApi.getHolidayStatistics({ year })
    statisticsData.value = response.data
    statisticsDialogVisible.value = true
  } catch (error) {
    console.error('获取统计信息失败:', error)
    ElMessage.error('获取统计信息失败')
  }
}

// 批量保存
const handleBatchSave = async () => {
  if (!batchForm.value.dateRange) {
    ElMessage.warning('请选择日期范围')
    return
  }

  try {
    const [startDate, endDate] = batchForm.value.dateRange
    const batchData: holidayApi.Holiday.SaveHolidayDataParams[] = []
    
    let currentDate = dayjs(startDate)
    const end = dayjs(endDate)
    
    while (currentDate.isSameOrBefore(end)) {
      const weekday = currentDate.day().toString()
      
      // 如果指定了星期几，只处理指定的星期几
      if (batchForm.value.weekdays.length === 0 || batchForm.value.weekdays.includes(weekday)) {
        batchData.push({
          date: currentDate.format('YYYY-MM-DD'),
          type: batchForm.value.type
        })
      }
      
      currentDate = currentDate.add(1, 'day')
    }
    
    if (batchData.length > 0) {
      await holidayApi.batchSaveHolidayData({ data: batchData })
      
      // 更新本地数据
      batchData.forEach(item => {
        holidayData.value[item.date] = item.type
      })
      
      ElMessage.success(`批量设置成功，共设置${batchData.length}天`)
      batchDialogVisible.value = false
    } else {
      ElMessage.warning('没有符合条件的日期')
    }
  } catch (error) {
    console.error('批量保存失败:', error)
    ElMessage.error('批量保存失败')
  }
}

// 监听当前日期变化
watch(currentDate, () => {
  loadHolidayData()
})

// 组件挂载时加载数据
onMounted(() => {
  loadHolidayData()
})
</script>

<style scoped lang="scss">
.holiday-manage {
  padding: 20px;
  background: #fff;
  border-radius: 8px;
}

.calendar-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  
  .header-actions {
    display: flex;
    gap: 10px;
  }
  
  .legend {
    display: flex;
    gap: 20px;
    
    .legend-item {
      display: flex;
      align-items: center;
      gap: 8px;
      font-size: 14px;
      
      .legend-color {
        width: 16px;
        height: 16px;
        border-radius: 4px;
        
        &.work {
          background: #67c23a;
        }
        
        &.holiday {
          background: #f56c6c;
        }
      }
    }
  }
}

.calendar-container {
  .calendar-grid {
    border: 1px solid #e4e7ed;
    border-radius: 8px;
    overflow: hidden;
    
    .week-header {
      display: grid;
      grid-template-columns: repeat(7, 1fr);
      background: #f5f7fa;
      
      .week-day {
        padding: 12px;
        text-align: center;
        font-weight: 600;
        color: #606266;
        border-right: 1px solid #e4e7ed;
        
        &:last-child {
          border-right: none;
        }
      }
    }
    
    .calendar-body {
      display: grid;
      grid-template-columns: repeat(7, 1fr);
      
      .calendar-cell {
        min-height: 80px;
        padding: 8px;
        border-right: 1px solid #e4e7ed;
        border-bottom: 1px solid #e4e7ed;
        cursor: pointer;
        transition: all 0.2s;
        position: relative;
        
        &:hover {
          background: #f0f9ff;
        }
        
        &:nth-child(7n) {
          border-right: none;
        }
        
        &.other-month {
          color: #c0c4cc;
          background: #fafafa;
        }
        
        &.today {
          background: #e1f3d8;
          
          .date-number {
            color: #67c23a;
            font-weight: bold;
          }
        }
        
        &.work-day {
          .date-type .type-badge.work {
            display: inline-block;
          }
        }
        
        &.holiday {
          .date-type .type-badge.holiday {
            display: inline-block;
          }
        }
        
        .date-number {
          font-size: 16px;
          font-weight: 500;
          margin-bottom: 4px;
        }
        
        .date-type {
          .type-badge {
            display: none;
            padding: 2px 6px;
            border-radius: 12px;
            font-size: 12px;
            color: white;
            
            &.work {
              background: #67c23a;
            }
            
            &.holiday {
              background: #f56c6c;
            }
          }
        }
      }
    }
  }
}

.edit-form, .batch-form {
  .form-item {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
    
    label {
      width: 100px;
      font-weight: 500;
      flex-shrink: 0;
      
      .required {
        color: #f56c6c;
        margin-right: 4px;
      }
    }
    
    .tip {
      font-size: 12px;
      color: #909399;
      margin-top: 5px;
    }
  }
}

.statistics-content {
  .statistics-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12px 0;
    border-bottom: 1px solid #f0f0f0;
    
    &:last-child {
      border-bottom: none;
    }
    
    .label {
      font-weight: 500;
      color: #606266;
    }
    
    .value {
      font-weight: 600;
      
      &.work {
        color: #67c23a;
      }
      
      &.holiday {
        color: #f56c6c;
      }
    }
  }
}

.dialog-footer {
  text-align: right;
}
</style>